<?php
require_once "BaseAction.php";                            
class Event_MemberController extends TTEvent_Base_Action 
{
	
	public function init(){
		parent::init();
		$this->_helper->layout->setLayout('event');
		$this->_helper->eventCommon->buildMainMenuBlock();
	}
	
	public function indexAction() {
		$this->_helper->layout->setLayout('event-detail');
		$eid = (int)$this->_getParam('eid', 0);
		$event = $this->_helper->modelLoader->getEventInfo($eid);
        $this->setTitle("Thành viên | ".$event->event_name);
		if(empty($event)){
			$this->_helper->getHelper('Redirector')->gotoUrlAndExit('/event/detail/'.$eid);
		}
		$user = $this->getUser();
		
		$isMember = $this->_helper->modelLoader->isEventMember($eid, $user->uid);
		$isAdmin = $this->_helper->modelLoader->isEventAdmin($eid, $user->uid);
		$isPublic = $this->_helper->privacy->isEventPublic($event->access);
		$isPrivate = $this->_helper->privacy->isEventPrivate($event->access);
		//var_dump(array($isAdmin, $isPublic, $isMember, $isPrivate));exit();
		if(!($isAdmin || $isPublic || ($isMember && $isPrivate)) ){
			$this->_helper->getHelper('Redirector')->gotoUrlAndExit('/event/detail/'.$eid);
		}

		
		$req = $this->getRequest();
		$memberModel = $this->loadModel('Member');
		
		if ($req->isPost())
		{
			$uids= $req->getPost("uid", array());
			$action = (int)$req->getPost("action", 0);
			
			if ($action== -1)
			{

				for ($i=0; $i<count($uids); $i++){
					$uid=$uids[$i];
					if ($this->_helper->modelLoader->isEventMember($eid, $uid)){
						$this->changeMemberStatus($eid, $uid, EVENT_USER_STATUS_NOTHING);
					}
				}
			}
		}
		
		$page = $req->getQuery('page',0);
		
		$this->view->event = $event;
		$this->view->uid = $user->uid;
		$this->view->isAdmin = $isAdmin;
		$this->view->isCanAddMember = ($isAdmin || ($isMember && $isPublic));
		
		$allMember = $this->_helper->modelLoader->getMemberList($eid);
		
		$pageInfo = array();
		$pageInfo['limit'] = 20;
		
		$pageInfo['total_item'] = count($allMember);
		$pageInfo['total_page'] = ceil($pageInfo['total_item']/$pageInfo['limit']);
		
		if($page >= $pageInfo['total_page'])
			$page = $pageInfo['total_page']-1;
		
		$pageInfo['page'] = $page;
		$memberList = $allMember;
		
		
		if($pageInfo['total_page'] > 0){
			$pageInfo['limit'] = 20;
			
			$from  = $page*$pageInfo['limit'];
			$length = min(array($pageInfo['limit'], $pageInfo['total_item']-$from));
			$memberList = array_slice($allMember, $from, $length);
		}
		
		$this->view->memberList = $memberList;
		$this->view->totalMember = $pageInfo['total_item'];
		
		$this->view->pager = $this->view->partial("pager.phtml", array("pageInfo" => $pageInfo, 'title'=>'thành viên tham gia', "ext_param" => "", "url" => "/event/member/".$eid));
		$this->view->htmlLeftCol = $this->_helper->eventCommon->buildHtmlEventLeftCol($eid);
		
	}
	
	public function invitedAction() {
		$this->_helper->layout->setLayout('event-detail');
		$eid = (int)$this->_getParam('eid', 0);
		$event = $this->_helper->modelLoader->getEventInfo($eid);
        $this->setTitle("Người được mời | ".$event->event_name);
		if(empty($event)){
			$this->_helper->getHelper('Redirector')->gotoUrlAndExit('/event/detail/'.$eid);
		}
		$user = $this->getUser();
		
		$isMember = $this->_helper->modelLoader->isEventMember($eid, $user->uid);
		$isAdmin = $this->_helper->modelLoader->isEventAdmin($eid, $user->uid);
		$isPublic = $this->_helper->privacy->isEventPublic($event->access);
		$isPrivate = $this->_helper->privacy->isEventPrivate($event->access);
		//var_dump(array($isAdmin, $isPublic, $isMember, $isPrivate));exit();
		if(!($isAdmin || $isPublic || ($isMember && $isPrivate)) ){
			$this->_helper->getHelper('Redirector')->gotoUrlAndExit('/event/detail/'.$eid);
		}

		
		$req = $this->getRequest();
		$memberModel = $this->loadModel('Member');
		
		$page = $req->getQuery('page',0);
		
		$this->view->event = $event;
		$this->view->uid = $user->uid;
		$this->view->isAdmin = $isAdmin;
		$this->view->isCanAddMember = ($isAdmin || ($isMember && $isPublic));
		
		$this->view->memberList = $memberModel->getGuestInvited($eid, EVENT_INVITE_REQUEST_SENT, $page);
		$pageInfo = $memberModel->getPageInfo();
		$this->view->totalMember = $pageInfo['total_item'];
		$this->view->pager = $this->view->partial("pager.phtml", array("pageInfo" => $pageInfo, 'title'=>'thành viên tham gia', "ext_param" => "", "url" => "/event/member/".$eid));
		$this->view->htmlLeftCol = $this->_helper->eventCommon->buildHtmlEventLeftCol($eid);
		
	}
	
	public function maybeAction() {
		$this->_helper->layout->setLayout('event-detail');
		$eid = (int)$this->_getParam('eid', 0);
		$event = $this->_helper->modelLoader->getEventInfo($eid);
		if(empty($event)){
			$this->_helper->getHelper('Redirector')->gotoUrlAndExit('/event/detail/'.$eid);
		}
        $this->setTitle("Thành viên có thể tham gia | ".$event->event_name);
		$user = $this->getUser();
		
		$isMember = $this->_helper->modelLoader->isEventMember($eid, $user->uid);
		$isAdmin = $this->_helper->modelLoader->isEventAdmin($eid, $user->uid);
		$isPublic = $this->_helper->privacy->isEventPublic($event->access);
		$isPrivate = $this->_helper->privacy->isEventPrivate($event->access);
		//var_dump(array($isAdmin, $isPublic, $isMember, $isPrivate));exit();
		if(!($isAdmin || $isPublic || ($isMember && $isPrivate)) ){
			$this->_helper->getHelper('Redirector')->gotoUrlAndExit('/event/detail/'.$eid);
		}

		
		$req = $this->getRequest();
		$memberModel = $this->loadModel('Member');
		
		$page = $req->getQuery('page',0);
		
		$this->view->event = $event;
		$this->view->uid = $user->uid;
		$this->view->isAdmin = $isAdmin;
		$this->view->isCanAddMember = ($isAdmin || ($isMember && $isPublic));
		
		$this->view->memberList = $memberModel->getGuestInvited($eid, EVENT_INVITE_REQUEST_MAYBE_ATTENDING, $page);
		$pageInfo = $memberModel->getPageInfo();
		$this->view->totalMember = $pageInfo['total_item'];
		$this->view->pager = $this->view->partial("pager.phtml", array("pageInfo" => $pageInfo, 'title'=>'thành viên tham gia', "ext_param" => "", "url" => "/event/member/".$eid));
		$this->view->htmlLeftCol = $this->_helper->eventCommon->buildHtmlEventLeftCol($eid);
		
	}
	
	public function leaveAction(){
		$ret = -1;
		$this->_helper->layout->disableLayout();
		$eid = (int)$this->_getParam('eid', 0);
		
		$req = $this->getRequest();
		if($req->isPost()){
			$user = $this->getUser();
			$event = $this->_helper->modelLoader->getEventInfo($eid);
			if($user->uid > 0 && !empty($event)){
				
				$memberStatus = $this->_helper->modelLoader->getMemberStatus($eid, $user->uid);
				if ($memberStatus['isMember']){
					$ret = $this->changeMemberStatus($eid, $user->uid, EVENT_USER_STATUS_NOTHING);
		
					if($ret==EVENT_USER_STATUS_NOTHING){
						//$this->sendLog('event/leave/member', $user->uid, $event->eid, $user->uid, $user->uid);
						$logevent = array(
				              'action'        =>  'event/leave',
				              'uid'           =>  $user->uid,
				              'username'      =>  $user->name,
				              'avatar'         =>  $user->avatar,
				              'eid'           =>  $eid,
				              'event_name'  =>  $event->event_name,
				              'event_logo'  =>  $event->logo,
				              'created'       =>  time()
				          );
				          ThriftLogger::thrift_log_get_content($logevent);
						
						$event = $this->_helper->modelLoader->getEventInfo($eid, false, false);
					}
				}
			}
		}
		echo $ret;
		exit();
	}
	
	public function joinAction(){
		$ret = 0;
		$this->_helper->layout->disableLayout();
		$eid = (int)$this->_getParam('eid', 0);
		
		$req = $this->getRequest();
		if($req->isPost()){
			$user = $this->getUser();
			$event = $this->_helper->modelLoader->getEventInfo($eid);
			if($user->uid > 0 && !empty($event)){
				
			
				$memberStatus = $this->_helper->modelLoader->getMemberStatus($eid, $user->uid);
				if(!$memberStatus['isMember']){
					if ($memberStatus['isInvited'] || $memberStatus['isMaybe']){
						//accept invite
						$ret = $this->acceptInvite($eid, $user->uid);
					}
					else if ($this->_helper->privacy->isEventPublic($event->access)){
						//public join
						$ret = $this->joinEvent($eid, $user->uid);
					}
				}
			}
			else if($user->uid <=0){
				$ret = -2;
			}
		}
		echo $ret;
		exit();
	}           
    
        /*/va
    public function timelineAction(){
        $this->_helper->layout->setLayout('event-detail');
        $eid = (int)$this->_getParam('eid', 0);
        $event = $this->_helper->modelLoader->getEventInfo($eid);
        $this->setTitle("Người được mời | ".$event->event_name);
        if(empty($event)){
            $this->_helper->getHelper('Redirector')->gotoUrlAndExit('/event/detail/'.$eid);
        }
        $user = $this->getUser();
        
        $isMember = $this->_helper->modelLoader->isEventMember($eid, $user->uid);
        $isAdmin = $this->_helper->modelLoader->isEventAdmin($eid, $user->uid);
        $isPublic = $this->_helper->privacy->isEventPublic($event->access);
        $isPrivate = $this->_helper->privacy->isEventPrivate($event->access);
        //var_dump(array($isAdmin, $isPublic, $isMember, $isPrivate));exit();
        if(!($isAdmin || $isPublic || ($isMember && $isPrivate)) ){
            $this->_helper->getHelper('Redirector')->gotoUrlAndExit('/event/detail/'.$eid);
        }
                
        $memberModel = $this->loadModel('Member');
        $timeline=$memberModel->getTimeLine($eid);
        $this->view->timeline=$timeline;
        
        $this->view->event = $event;
        $this->view->uid = $user->uid;
        $this->view->isAdmin = $isAdmin;
        $this->view->isCanAddMember = ($isAdmin || ($isMember && $isPublic));

                $this->view->htmlLeftCol = $this->_helper->eventCommon->buildHtmlEventLeftCol($eid);  
 
       //// $this->_helper->eventCommon->cleanUserEventCache
        
    } 
    public function datachartAction(){
        $eid = (int)$this->_getParam('eid', 0);
        $this->_helper->layout->disableLayout();
        $memberModel = $this->loadModel('Member'); 
        $mm=$memberModel->getEventMemberInfo($eid,"min max");
        $min_joindate=$mm[0]->min;
        $max_joindate=$mm[0]->max;
        $t1=$min_joindate;
        
        if(($max_joindate-$min_joindate)<=14*24*60*60){         // <= 14 ngay
                   
            for($i=0;$i<=ceil(($max_joindate-$min_joindate)/(60*60*24));$i++)
            {
                $t2=$t1+60*60*24;
                $data[$i]=$memberModel->getNumMember($eid,$t1,$t2);
                $t1=$t2;
                $data2[$i]=$i+1;
            }
            $data[]=0;
            $data[]=0;
            $data2[]="";
            $data2[]="...".date("d/m/Y",time());
            $t="Ngày";
            $this->view->y_max=10*ceil(max($data)/10);   
        }        
        if(12*24*60*60< ($max_joindate-$min_joindate) && ($max_joindate-$min_joindate)<=8*7*24*60*60){    //  <8 tuan
            for($i=0;$i<=ceil(($max_joindate-$min_joindate)/(7*60*60*24));$i++)
            {
                $t2=$t1+7*60*60*24;
                $data[$i]=$memberModel->getNumMember($eid,$t1,$t2);
                $t1=$t2;
                $data2[$i]=$i+1;
            }
            $data[]=0;
            $data[]=0;
            $data2[]="";
            $data2[]="...".date("d/m/Y",time());
            $t="Tuần";
            $this->view->y_max=10*ceil(max($data)/10);   
        }        
        if(8*7*24*60*60< ($max_joindate-$min_joindate) && ($max_joindate-$min_joindate)<=12*30*24*60*60){  // < 1 nam
            for($i=0;$i<=ceil(($max_joindate-$min_joindate)/(30*60*60*24));$i++)
            {
                $t2=$t1+30*60*60*24;
                $data[$i]=$memberModel->getNumMember($eid,$t1,$t2);
                $t1=$t2;
                $data2[$i]=$i+1;
            }
            $data[]=0;
            $data[]=0;
            $data2[]="";
            $data2[]="...".date("d/m/Y",time());
            $t="Tháng";
            $this->view->y_max=10*ceil(max($data)/10);   
        }       
        if(($max_joindate-$min_joindate)>12*30*24*60*60){         // >1 nam
            for($i=0;$i<=ceil(($max_joindate-$min_joindate)/(360*60*60*24));$i++)
            {
                $t2=$t1+360*60*60*24;
                $data[$i]=$memberModel->getNumMember($eid,$t1,$t2);
                $t1=$t2;
                $data2[$i]=$i+1;
            }
            $data[]=0;
            $data[]=0;
            $data2[]="";
            $data2[]="...".date("d/m/Y",time());
            $t="Năm";
            $this->view->y_max=10*ceil(max($data)/10); 
        }

        $values=implode(",",$data);
        $labels=implode(",",$data2);
        $labels=$t.$labels;
                                    
        $this->view->values=$values;
        $this->view->labels=$labels;
    }
    
  
    s
    //{va open flash chart
    public function open_flash_chart_object_str( $width, $height, $url, $use_swfobject=true, $base='tamtay.vn' )
        {
            //
            // return the HTML as a string
            //
            return $this->_ofc( $width, $height, $url, $use_swfobject, $base );
        }

    public function open_flash_chart_object( $width, $height, $url, $use_swfobject=true, $base='tamtay.vn/' )
    {
        //
        // stream the HTML into the page
        //
        echo $this->_ofc( $width, $height, $url, $use_swfobject, $base );
    }

    public function _ofc( $width, $height, $url, $use_swfobject, $base )
    {
        //
        // I think we may use swfobject for all browsers,
        // not JUST for IE...
        //
        //$ie = strstr(getenv('HTTP_USER_AGENT'), 'MSIE');
        
        //
        // escape the & and stuff:
        //
        $url = urlencode($url);
        
        //
        // output buffer
        //
        $out = array();
        
        //
        // check for http or https:
        //
        if (isset ($_SERVER['HTTPS']))
        {
            if (strtoupper ($_SERVER['HTTPS']) == 'ON')
            {
                $protocol = 'https';
            }
            else
            {
                $protocol = 'http';
            }
        }
        else
        {
            $protocol = 'http';
        }
        
        //
        // if there are more than one charts on the
        // page, give each a different ID
        //
        global $open_flash_chart_seqno;
        $obj_id = 'chart';
        $div_name = 'flashcontent';
        
        //$out[] = '<script type="text/javascript" src="'. $base .'js/ofc.js"></script>';
        
        if( !isset( $open_flash_chart_seqno ) )
        {
            $open_flash_chart_seqno = 1;
            $out[] = '<script type="text/javascript" src="'. $base .'js/swfobject.js"></script>';
        }
        else
        {
            $open_flash_chart_seqno++;
            $obj_id .= '_'. $open_flash_chart_seqno;
            $div_name .= '_'. $open_flash_chart_seqno;
        }
        
        if( $use_swfobject )
        {
        // Using library for auto-enabling Flash object on IE, disabled-Javascript proof  
        $out[] = '<div id="'. $div_name .'"></div>';
        $out[] = '<script type="text/javascript">';
        $out[] = 'var so = new SWFObject("'. $base .'open-flash-chart.swf", "'. $obj_id .'", "'. $width . '", "' . $height . '", "9", "#FFFFFF");';
        //$out[] = 'so.addVariable("width", "' . $width . '");';
        //$out[] = 'so.addVariable("height", "' . $height . '");';
        $out[] = 'so.addVariable("data", "'. $url . '");';
        $out[] = 'so.addParam("allowScriptAccess", "sameDomain");';
        $out[] = 'so.write("'. $div_name .'");';
        $out[] = '</script>';
        $out[] = '<noscript>';
        }

        $out[] = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="' . $protocol . '://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" ';
        $out[] = 'width="' . $width . '" height="' . $height . '" id="ie_'. $obj_id .'" align="middle">';
        $out[] = '<param name="allowScriptAccess" value="sameDomain" />';
        $out[] = '<param name="movie" value="'. $base .'open-flash-chart.swf?width='. $width .'&height='. $height . '&data='. $url .'" />';
        $out[] = '<param name="quality" value="high" />';
        $out[] = '<param name="bgcolor" value="#FFFFFF" />';
        $out[] = '<embed src="'. $base .'open-flash-chart.swf?data=' . $url .'" quality="high" bgcolor="#FFFFFF" width="'. $width .'" height="'. $height .'" name="'. $obj_id .'" align="middle" allowScriptAccess="sameDomain" ';
        $out[] = 'type="application/x-shockwave-flash" pluginspage="' . $protocol . '://www.macromedia.com/go/getflashplayer" id="'. $obj_id .'"/>';
        $out[] = '</object>';

        if ( $use_swfobject ) {
        $out[] = '</noscript>';
        }
        
        return implode("\n",$out);
    }
    
    //va }*/
	public function maybejoinAction(){
		$ret = 0;
		$this->_helper->layout->disableLayout();
		$eid = (int)$this->_getParam('eid', 0);
		
		$req = $this->getRequest();
		if($req->isPost()){
			$user = $this->getUser();
			$event = $this->_helper->modelLoader->getEventInfo($eid);
			if($user->uid > 0 && !empty($event)){
				
			
				$memberStatus = $this->_helper->modelLoader->getMemberStatus($eid, $user->uid);
				if(!$memberStatus['isMember'] && ($memberStatus['isInvited'] || $memberStatus['isNot']) && !$memberStatus['isMaybe']){
					$ret = $this->maybeJoinEvent($eid, $user->uid);
				}
			}
			else if($user->uid <=0){
				$ret = -2;
			}
		}
		echo $ret;
		exit();
	}
	
	public function notjoinAction(){
		$ret = 0;
		$this->_helper->layout->disableLayout();
		$eid = (int)$this->_getParam('eid', 0);
		
		$req = $this->getRequest();
		if($req->isPost()){
			$user = $this->getUser();
			$event = $this->_helper->modelLoader->getEventInfo($eid);
			if($user->uid > 0 && !empty($event)){
				
			
				$memberStatus = $this->_helper->modelLoader->getMemberStatus($eid, $user->uid);
				if(!$memberStatus['isMember'] && ($memberStatus['isInvited'] || $memberStatus['isMaybe']) && !$memberStatus['isNot']){
					$ret = $this->notJoinEvent($eid, $user->uid);
				}
			}
			else if($user->uid <=0){
				$ret = -2;
			}
		}
		echo $ret;
		exit();
	}
	
	public function requestAction(){
		$ret = 0;
		$this->_helper->layout->disableLayout();
		$eid = (int)$this->_getParam('eid', 0);
		
		$req = $this->getRequest();
		if($req->isPost()){
			$user = $this->getUser();
			$event = $this->_helper->modelLoader->getEventInfo($eid);
			
			if($user->uid > 0 && !empty($event)){
				$memberModel = $this->loadModel('Member');
				$memberStatus = $this->_helper->modelLoader->getMemberStatus($eid, $user->uid);
				if(!$memberStatus['isMember'] && !$memberStatus['isRequest']){
					
					if ($this->_helper->privacy->isEventPublic($event->access) || $memberStatus['isInvited']){
						//public join
						$ret = $this->joinEvent($eid, $user->uid);
						$ret = EVENT_USER_STATUS_MEMBER;
					}
					else if($this->_helper->privacy->isEventPrivate($event->access)){
						$memberModel = $this->loadModel('Member');
						$memberModel->insertRequest($eid, $user->uid, REQUEST_EVENT_REQUEST_TYPE);
						$memberModel->changeMemberCount($eid, REQUEST_EVENT_REQUEST_TYPE, "", 1);
						$memberModel->updateUserStatistic($user->uid, REQUEST_EVENT_REQUEST_TYPE);
						$ret = 1;
					}
				}
			}
			else if($user->uid <=0){
				$ret = -2;
			}
		}
		echo $ret;
		exit();
	}

	function acceptAction()
	{
		$this->_helper->layout->setLayout('event-detail');
		$eid = (int)$this->_getParam('eid', 0);
		
		$err = $this->checkEventEditPrivacy($eid, true, 'info');
		
		if(count($err) > 0){
			$this->_helper->getHelper('Redirector')->gotoUrlAndExit('/event/detail/'.$eid);
		}
		
		$user = $this->getUser();
		$event = $this->_helper->modelLoader->getEventInfo($eid);
		$req = $this->getRequest();
		$memberModel = $this->loadModel('Member');
		$this->setTitle("Thành viên xin tham gia | ".$event->event_name);
        
		if ($req->isPost())
		{
			$uids= $req->getPost("uid", array());
			$action = (int)$req->getPost("action", 0);
			
			if ($action== 1){
				for ($i=0; $i<count($uids); $i++){
					$uid=$uids[$i];
					if ($memberModel->isWaitingAcceptRequest($eid, $uid)){
						
						$status = $this->changeMemberStatus($eid, $uid, EVENT_USER_STATUS_MEMBER);
						if($status==EVENT_USER_STATUS_MEMBER){
							$event = $this->_helper->modelLoader->getEventInfo($eid, false, false);
						}
					}
				}
			}
			else if ($action== -1)
			{
				for ($i=0; $i<count($uids); $i++){
					$uid=$uids[$i];
					if ($memberModel->isWaitingAcceptRequest($eid, $uid)){
						$this->changeMemberStatus($eid, $uid, EVENT_USER_STATUS_NOTHING);
					}
				}
			}
		}
		
		$isAdmin = $this->_helper->modelLoader->isEventAdmin($eid, $user->uid);
		$isMember = $this->_helper->modelLoader->isEventMember($eid, $user->uid);
		$isPublic = $this->_helper->privacy->isEventPublic($event->access);
		$page = $req->getQuery('page',0);
		
		$this->view->event = $event;
		$this->view->isAdmin = $isAdmin;
		$this->view->isCanAddMember = ($isAdmin || ($isMember && $isPublic));
		
		$this->view->waitingAcceptList = $memberModel->getRequestList($eid, $page);
		$pageInfo = $memberModel->getPageInfo();
		$this->view->totalRequest = $pageInfo['total_item'];
		$this->view->pager = $this->view->partial("pager.phtml", array("pageInfo" => $pageInfo, 'title'=>'thành viên xin tham gia', "ext_param" => "", "url" => "/event/accept/".$eid));
		$this->view->htmlLeftCol = $this->_helper->eventCommon->buildHtmlEventLeftCol($eid);
	}
	
	
//add/remove member to invite pending list (Ajax called)
	//path: /event/invite/event_id/uid=member_id&add=1[remove=1]
	public function inviteAction()
	{
		$this->_helper->layout->disableLayout();
		$eid = (int)$this->_getParam('eid', 0);
		$invitedUid = (int)$this->_getParam('uid', 0);
		
		$err = $this->checkEventEditPrivacy($eid, true, 'member');
		
		if(count($err) > 0){
			exit();
		}
		
		$user = $this->getUser();
		
		$remove = (int)$this->getRequest()->getQuery('remove', 0);
		$add = (int)$this->getRequest()->getQuery('add', 0);
		//$event = $this->_helper->modelLoader->getEventInfo($eid);
		
		if ($this->_helper->modelLoader->isEventMember($eid, $invitedUid))
		{
			exit();
		}
		
		if ($add==1)
		{
			$rs= $this->addPending($eid, $invitedUid, $user->uid);
			echo $rs;
			exit();
		}
		else if ($remove==1){
			$memberModel = $this->loadModel('Member');
			$memberModel->removePending($eid, $invitedUid, $user->uid);
			exit();
		}

	}
	
	public function addPending($eid, $uid, $eventAdminUid){
		if ($this->_helper->modelLoader->isEventMember($eid, $uid))
			return 0;
		
		$memberModel = $this->loadModel('Member');
		return $memberModel->addPending($eid, $uid, $eventAdminUid);
		
	}
	
	public function attendAction(){
		$this->_helper->layout->disableLayout();
		$eid = (int)$this->_getParam('eid', 0);
		$user = $this->getUser();
		
		if($eid && $user->uid){
			$req  = $this->getRequest();
			if($req->isPost()){
				$newStatus = $req->getPost('attending_status');
				$status = $this->changeMemberStatus($eid, $user->uid, $newStatus);
			}
		}
		echo $status;
		exit();
	}
	
	public function memberAction(){
		
		$eid = (int)$this->_getParam('eid', 0);
		$user = $this->getUser();
		if(!$user->uid)
			$this->requireLogin();
			
		$err = $this->checkEventEditPrivacy($eid, true, 'member');
		
		if(!$eid)
			$this->_helper->getHelper('Redirector')->gotoUrlAndExit('/event');
		if(count($err) > 0){
			$this->_helper->getHelper('Redirector')->gotoUrlAndExit('/event/detail/'.$eid);
		}

		$event = $this->_helper->modelLoader->getEventInfo($eid);
		
		$this->_helper->eventCommon->buildMainMenuBlock();
		$this->_helper->layout->setLayout('event-edit');
        $this->setTitle("Mời bạn bè: ".$event->event_name);
		
		$err = array();
		$req = $this->getRequest();
		
		$this->view->action = 'member';
		$this->view->event = $event;
		
		$memberModel = $this->loadModel('Member');
		
		$view="";
		if ($req->isPost())
		{
			$invite = (int)$req->getPost('invite', 0);
			if($invite==1){
				
				$inviteMsg = $req->getPost('invite_msg', '');
				$memberModel = $this->loadModel('Member');
				$uids = $memberModel->sendInvite($eid, $user->uid, $inviteMsg);
				if(is_array($uids) && count($uids) > 0){
					//$this->sendLog('event/invite/member', $user->uid, $eid, $uids, $uids);
				}
				
				$this->_helper->getHelper('Redirector')->gotoUrlAndExit('/event/edit/member/'.$eid."?msg=1");
			}
			
			$view=$req->getPost('view', 0);
			if ($view!="1" && $view!="-1" && $view!="0" && $view!="2")
			{
				$view=1;
			}
		}
		else
		{
			$view=1;
		}
		
		$data=array();

		switch($view){
			case 1:
				$this->view->member_list  = $this->_helper->modelLoader->getMemberList($eid);
				break;
			case -1:
				$this->view->member_list  = $memberModel->getGuestInvited($eid, EVENT_INVITE_REQUEST_SENT, 0, 40);
				break;
			case 0:
				$this->view->member_list  = $memberModel->getGuestInvited($eid, EVENT_INVITE_REQUEST_NOT_ATTENDING, 0, 40);
				break;
			case 2:
				$this->view->member_list  = $memberModel->getGuestInvited($eid, EVENT_INVITE_REQUEST_MAYBE_ATTENDING, 0, 40);
				break;
			
		}

		$this->view->friend_list =$memberModel->getFriendNotInEvent($eid, $user->uid);
		
		$friend_member_list = array();
		if(is_array($this->view->friend_list ) && count($this->view->friend_list )){
			$uids = array();
			foreach($this->view->friend_list  as $fObj){
				$uids[] = $fObj->uid;
			}
			$friend_member_list= $memberModel->getFriendInEvent($eid, $uids);
		}
		$this->view->friend_member_list  = $friend_member_list;
		
		
		$this->view->request_invited_list  = $memberModel->getRequestInvitedUids($eid);;
		
		$this->view->pending_list = $memberModel->getUserInvitePending($eid, $user->uid);
		
		//var_dump($this->view->request_invited_list);exit();
		$msgs = array('');
		$msgs[1]="Thư mời tham gia sự kiện đã được gửi đến những người bạn của bạn";
		$this->view->msg =$msgs[$req->getQuery('msg', 0)];
		$this->view->view =$view;
		$this->view->user =$user;
		$this->view->isAdmin = $this->_helper->modelLoader->isEventAdmin($eid, $user->uid);
		$this->view->isSiteAdmin = $this->isAdmin();
	}
	
	public function makeadminAction(){
		
		$this->_helper->layout->disableLayout();
		$user = $this->getUser();
		$targetUid = (int)$this->_getParam('uid', 0);
		$eid = (int)$this->_getParam('eid', 0);
		$msg="success";
		$result=0;
		$st = "";
		if(!$user->uid){
			$msg = "invalid login";
		}
		else if(!$targetUid){
			$msg = "invalid target user";
		}
		else if(!$eid){
			$msg = "invalid event";
		}
		else if(!$this->_helper->modelLoader->isEventAdmin($eid, $user->uid)){
			$msg = "invalid admin";
		}
		else{
			$memberModel = $this->loadModel('Member');
			$targetUser = $memberModel->getUserInfo($targetUid);
			if($targetUser){
				$result=1;
				
				if($memberModel->makeAdmin($eid, $targetUid)){
				
					$u_name=$targetUser->first_name . " " . $targetUser->last_name;
					if ($targetUser->uid==$user->uid){
						$me=1;
					}
					else{
						$me=0;
					}
					
					$st=$st . '<a onclick="event_member.removeMember('.$eid.', ' . $targetUser->uid . ', \'' . $u_name . '\', ' . $me . ',1); return false;" href="#">Loại bỏ</a> | ';
					$st=$st . '<a onclick="event_member.removeAdmin('.$eid.', ' . $targetUser->uid . ', \'' . $u_name . '\', ' . $me . '); return false;" href="#">Hủy admin</a>';
					$st=addslashes($st);
				}
			}
		
		}
	
		$response="{status: $result, msg: '$msg', el: '$st'}";
		echo $response;
		exit();
	}
	
	public function removeadminAction(){
		$this->_helper->layout->disableLayout();
		$user = $this->getUser();
		$targetUid = (int)$this->_getParam('uid', 0);
		$eid = (int)$this->_getParam('eid', 0);
		$msg="success";
		$result=0;
		$st = "";
		if(!$user->uid){
			$msg = "invalid login";
		}
		else if(!$targetUid){
			$msg = "invalid target user";
		}
		else if(!$eid){
			$msg = "invalid event";
		}
		else if(!$this->_helper->modelLoader->isEventAdmin($eid, $user->uid)){
			$msg = "invalid admin";
		}
		else{
			$memberModel = $this->loadModel('Member');
			$targetUser = $memberModel->getUserInfo($targetUid);
			if($targetUser){
				$result=1;
				
				if($memberModel->removeAdmin($eid, $targetUid)){
				
					$u_name=$targetUser->first_name . " " . $targetUser->last_name;
					if ($targetUser->uid==$user->uid){
						$me=1;
					}
					else{
						$me=0;
					}
					
					$st=$st . '<a onclick="event_member.removeMember('.$eid.', ' . $targetUser->uid . ', \'' . $u_name . '\', ' . $me . ',1); return false;" href="#">Loại bỏ</a> | ';
					$st=$st . '<a onclick="event_member.makeAdmin('.$eid.', ' . $targetUser->uid . ', \'' . $u_name . '\'); return false;" href="#">Gán admin</a>';
					$st=addslashes($st);
				}
			}
		
		}
	
		$response="{status: $result, msg: '$msg', el: '$st'}";
		echo $response;
		exit();
	}
	
	public function removememberAction(){
		$this->_helper->layout->disableLayout();
		$user = $this->getUser();
		$targetUid = (int)$this->_getParam('uid', 0);
		$eid = (int)$this->_getParam('eid', 0);
		$msg="success";
		$result=0;
		$st = "";
		if(!$user->uid){
			$msg = "invalid login";
		}
		else if(!$targetUid){
			$msg = "invalid target user";
		}
		else if(!$eid){
			$msg = "invalid event";
		}
		else if(!$this->_helper->modelLoader->isEventAdmin($eid, $user->uid)){
			$msg = "invalid admin";
		}
		else{
			$result=1;
			$ret = $this->changeMemberStatus($eid, $targetUid, EVENT_USER_STATUS_NOTHING);
	
			if($ret==EVENT_USER_STATUS_NOTHING){
				$event = $this->_helper->modelLoader->getEventInfo($eid, false, false);
			}
		}
	
		$response="{status: $result, msg: '$msg', el: '$st'}";
		echo $response;
		exit();
	}
	
	
	public function checkEventEditPrivacy($eid, $needEventExist=false, $type="info"){
		$eid = (int)$eid;
		$err = array();
		$user = $this->getUser();
		if(!$user->uid){
			$err['chk_privacy'] = 'Bạn cần đăng nhập.';
		}
			
		
		if($needEventExist && !$eid){
			$err['chk_privacy'] = 'Không tồn tại sự kiện.';
			return $err;
		}
		if($eid > 0){
			$event_old = $this->_helper->modelLoader->getEventInfo($eid);
			if(!$event_old){
				$err['chk_privacy'] = 'Không tồn tại sự kiện ứng với ID: '.$eid;
			}
			// chi co admin hoac nguoi tao moi co quyen sua
			switch ($type){
				case 'member':
					if(!($this->_helper->privacy->isEventPublic($event_old->access) && $this->_helper->modelLoader->isEventMember($eid, $user->uid)) &&
					!$this->_helper->modelLoader->isEventAdmin($eid, $user->uid)){
						$err['chk_privacy'] = 'Bạn không có quyền mời, sửa thành viên sự kiện này.';
					}
					break;
				case 'info':
				default:
					if(!$this->_helper->modelLoader->isEventAdmin($eid, $user->uid)){
						$err['chk_privacy'] = 'Bạn không có quyền sửa sự kiện này';
					}
					break;
			}
		}

		return $err;
	}
	
	public function changeMemberStatus($eid, $uid, $newStatus){
		
		$event = $this->_helper->modelLoader->getEventInfo($eid);
		$isPublic = $this->_helper->privacy->isEventPublic($event->access);
		$isPrivate = $this->_helper->privacy->isEventPrivate($event->access);
		$isSecure = $this->_helper->privacy->isEventSecure($event->access);
		
		$memberModel = $this->loadModel('Member');
		
		$memberStatus = $this->_helper->modelLoader->getMemberStatus($eid, $uid);
		
		$oldStatus = 0;
		
		if($memberStatus['isAdmin'])
			$oldStatus = EVENT_USER_STATUS_ADMIN;
		else if($memberStatus['isMember'])
			$oldStatus = EVENT_USER_STATUS_MEMBER;
		else if($memberStatus['isRequest'])
			$oldStatus = EVENT_USER_STATUS_REQUEST;
		else if($memberStatus['isInvited'])
			$oldStatus = EVENT_USER_STATUS_INVITED;
		else if($memberStatus['isMaybe'])
			$oldStatus = EVENT_USER_STATUS_MAYBE;
		else if($memberStatus['isNot'])
			$oldStatus = EVENT_USER_STATUS_NOT;
		
		$canChange = false;
		$canRemoveOld = true;
		
		if($newStatus == EVENT_USER_STATUS_MEMBER){
			if($memberStatus['isInvited'] || $memberStatus['isMaybe'] || $isPublic || $memberStatus['isRequest']|| $memberStatus['isNot'])
				$canChange = true;
		}
		else if($newStatus == EVENT_USER_STATUS_MAYBE){
			if($memberStatus['isInvited'] || $memberStatus['isNot']){
				$canChange = true;
				$canRemoveOld = false;
			}
		}
		else if($newStatus == EVENT_USER_STATUS_NOT){
			if($memberStatus['isInvited'] || $memberStatus['isMaybe'] || $memberStatus['isMember'])
				$canChange = true;
			if($memberStatus['isInvited'] || $memberStatus['isMaybe'])
				$canRemoveOld = false;
		}
		else if($newStatus == EVENT_USER_STATUS_NOTHING){
			$canChange = true;
		}
		
		if($canChange){
			$status = 0;
			if($oldStatus > 0 && $canRemoveOld){
				$status = $memberModel->removeMemberStatus($eid, $uid, $oldStatus);
			}
			
			$eventWasDeleted = false;
			if($status==1){
				// remove event
				$event = $this->_helper->modelLoader->getEventInfo($eid, false, false);
				if($event->member_count <= 0 ){
					$eventModel = $this->loadModel('Event');
					if($eventModel->destroyEvent($eid))
						$eventWasDeleted = true;
				}
			}
			$this->_helper->eventCommon->cleanUserEventCache($eid, $uid, $oldStatus, $newStatus);
			if(!$eventWasDeleted ){
				if($newStatus>0){
					$memberModel->memberNewStatus($eid, $uid, $newStatus, $canRemoveOld);
					return $newStatus;
				}
			}
			else{
				return -1;
			}
			
		}
		return 0;
	}
	
	
	
	private function joinEvent($eid, $uid){
		
		$status = $this->changeMemberStatus($eid, $uid, EVENT_USER_STATUS_MEMBER);
		
		if($status==EVENT_USER_STATUS_MEMBER){
			//$this->sendLog('event/join/member', $uid, $eid, $uid, $uid);
			$user = $this->getUser();
			$event = $this->_helper->modelLoader->getEventInfo($eid);
			$logevent = array(
	            'action'        =>  'event/join',
	            'uid'           =>  $user->uid,
	            'username'      =>  $user->name,
	            'avatar'         =>  $user->avatar,
	            'eid'           =>  $eid,
	            'event_name'  =>  $event->event_name,
	            'event_logo'  =>  $event->logo,
	            'created'       =>  time()
	        );
			ThriftLogger::thrift_log_get_content($logevent);
			
			$this->_helper->modelLoader->getEventInfo($eid, false, false);
		}
		return $status;
	}
	
	private function maybeJoinEvent($eid, $uid){
		
		$status = $this->changeMemberStatus($eid, $uid, EVENT_USER_STATUS_MAYBE);
		
		if($status==EVENT_USER_STATUS_MAYBE){
			$this->_helper->modelLoader->getEventInfo($eid, false, false);
		}
		return $status;
	}
	
	private function notJoinEvent($eid, $uid){
		
		$status = $this->changeMemberStatus($eid, $uid, EVENT_USER_STATUS_NOT);
		
		if($status==EVENT_USER_STATUS_NOT){
			$this->_helper->modelLoader->getEventInfo($eid, false, false);
		}
		return $status;
	}
	
	private function acceptInvite($eid, $uid){
		return $this->joinEvent($eid, $uid);
	}
	
}
